package cn.ainit.base.approve;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.ainit.base.approve.entity.SysApprove;
import cn.ainit.common.ReturnObject;
import cn.ainit.sys.menu.SessionCont;

@Controller
@RequestMapping("/approve")
public class ApproveController {

	private ApproveService approveService;
	@Resource
	public void setApproveService(ApproveService approveService) {
		this.approveService = approveService;
	}


	/**
	 * 通过ID查询这个单据的所有审批数据
	 * @param djId
	 * 单据Id
	 * @param request
	 * @return 返回apply.jsp 并将查询出来的list放入request中
	 * @throws Exception
	 */
	@RequestMapping("/approveDJ")
	public String approvesDJ(ApproveReturnObj oldApReturnObj,
			HttpServletRequest request, HttpSession session) throws Exception {
		// 根据Id去查找审批表中所有的数据
		ApproveReturnObj approveReturnObj = oldApReturnObj;
		try {
			String approveGrade = "";
			try {
				// 得到单据的dsName(Name当做审批名称)
				approveReturnObj.setDsName(this.approveService.getDsName(oldApReturnObj.getDsId()));
				// 审批单据的的所有的审批列表111
				approveReturnObj.setListAppr(loadApplyListByDjId(oldApReturnObj.getDjId(),oldApReturnObj.getDsId(), session));
			} catch (Exception e) {
				e.printStackTrace();
			}
			request.setAttribute("approveReturnObj",approveReturnObj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "pages/commen/approve";
	}

	@RequestMapping("/loadApproveStyle")
	@ResponseBody
	public ApproveReturnObj loadApproveStyle(String djId, String dsId,HttpServletRequest request, HttpSession session) throws Exception {
		ApproveReturnObj approveReturnObj = new ApproveReturnObj();
		String verifyPass = "S001"; // 审批通过
		String verifyNoPass = "S002"; // 审批不通过
		String verifyReject = "S004"; // 审批被驳回(只有二审和三审有驳回上一级)
		// 审批单据的的所有的审批列表
		List<SysApprove> sysApprovesList = loadApplyListByDjId(djId,dsId, session);
		Object uid = session.getAttribute(SessionCont.uid);
		// 判断用户存不存在
		if (uid == null || "".equals(uid.toString())) {
			approveReturnObj.setIsApproveRight(0);
			approveReturnObj.setMsg("fail");
			approveReturnObj.setInfo("用户没有登录，请重新登陆");
			return approveReturnObj;
		} else {
			for (int i = 0; i < sysApprovesList.size(); i++) {
				String tempApproveResult = sysApprovesList.get(i)
				.getIsExamine();
				//未审批和审批不通过是允许用户修改的
				if (tempApproveResult == null
						|| tempApproveResult.trim().equals(verifyNoPass.trim())
						|| tempApproveResult.trim().equals("")
						|| tempApproveResult.trim().equals(verifyReject)) {
					// 得到单据的审批级别
					Integer level = sysApprovesList.get(i).getApproveLevel();
					approveReturnObj.setApproveGrade(level);
					// 判断登录人有没有该单据的审批权限
					// 1.得到改单据审批流程中该级别设置设置审批的权限组
					String examineManFkVal = approveService.getExamineManFkVal(level,dsId,"");

					// 判断当前登录人是否在该权限组内
					Integer isRight = approveService.getIsApproveRight(
							examineManFkVal, djId, dsId, session);
					approveReturnObj.setIsApproveRight(isRight);
					System.out.println("==================调用审批过程结果（0：没有权限 1：有权限）isRight："+isRight);
					// 判断该级别的单据时候已经审批通过
					if (sysApprovesList.get(i).getIsExamine() != null
							&& sysApprovesList.get(i).getIsExamine().trim()
							.equals(verifyPass.trim())) {
						approveReturnObj.setCheckApprovePass(true);
					} else {
						approveReturnObj.setCheckApprovePass(false);
					}
					break;
				}
				if(tempApproveResult.trim().equals(verifyPass)&&sysApprovesList.get(i).getApproveLevel()==approveService.maxDjLevel(sysApprovesList.get(i))){
					//在sys_datastore 中判断本单据是否可以驳回（IS_REJECT）
					String isReject=approveService.isRejectByDsId(dsId, "");
					approveReturnObj.setIsReject(isReject);
					// 1.得到改单据审批流程中该级别设置设置审批的权限组
					String examineManFkVal = approveService.getExamineManFkVal(sysApprovesList.get(i).getApproveLevel(),dsId,"");
					// 判断当前登录人是否在该权限组内
					Integer isRight = approveService.getIsApproveRight(
							examineManFkVal, djId, dsId, session);
					System.out.println("==================调用审批过程结果（0：没有权限 1：有权限）isRight："+isRight);
					approveReturnObj.setIsApproveRight(isRight);
				}
			}
		}
		return approveReturnObj;
	}



	/***
	 * 判断该单据是否有要审批的数据
	 * 
	 * @param djId
	 * @param djType
	 * @param djCode
	 * @param dsId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("listAppr")
	@ResponseBody
	public ReturnObject listAppr(String djId, String djType, String djCode,
			String dsId, HttpServletRequest request) throws Exception {
		ReturnObject returnObject = new ReturnObject();
		List<SysApprove> listAppr = new ArrayList<SysApprove>();
		try {
			String flag = approveService.getApprove(djId, djType, djCode); // 执行存储过程生成单据的审批数据
			if (flag.equals("0")) {// '0'; --如果审批表还是没有记录 就代表 审批结果已经完成了
				returnObject.setMsg("该单据已经审批完成");
			} else if (flag.equals("1")) { // 该单据有审批数据
				listAppr = this.approveService.listApproves(djId); // 在approve中有记录的时候才查询
				returnObject.setObjList(listAppr);
			} else { // 生成审批单据的时候发生异常
				returnObject.setMsg(flag);
				throw new Exception(flag);

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnObject;
	}



	/****
	 *根据dsId 得到某个流程节点的最高的等级
	 * 
	 * @param dsId
	 * @param config
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("getMaxAppleLevel")
	@ResponseBody
	public ReturnObject getMaxApplyLevelByDsId(String dsId, String config,HttpServletRequest request) throws Exception {
        ReturnObject rt = new ReturnObject(); //false || 0代表没有审批
		try {
            rt.setFlag(true);
			String level = this.approveService.getMaxApplyLevelByDsId(dsId,config);
            if(level == null || level.equals("")){
                rt.setFlag(false);
            }
		} catch (Exception e) {
            rt.setFlag(false);
			e.printStackTrace();
		}
		return rt;
	}

	/****
	 * 根据djId得到该approve的列表
	 * 
	 * @param djId
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("loadApplyListByDjId")
	@ResponseBody
	public List loadApplyListByDjId(String djId,String dsId, HttpSession session) {
		List<SysApprove> list = null;
		try {
			list = this.approveService.dataById(djId,dsId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/****
	 * 点击提交    调用存储过程生成单据approveList数据
	 * @param djId
	 * @param dsId
	 * @param djType
	 * @param djCode
	 * @throws Exception
	 */
	@RequestMapping("produceApproveList")
	@ResponseBody
	public ReturnObject produceApproveList(String djId, String dsId,
			String djType, String djCode, HttpSession session) throws Exception {
		ReturnObject returnObject = new ReturnObject();
		try {
			returnObject = approveService.produceApproveList(djId, dsId,djType, djCode,session);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnObject;
	}

	/*******************************
	 *最高等级审批通过的时候
	 ******************************* 
	 */
	@RequestMapping("/approveMaxLevel")
	@ResponseBody
	public boolean approveMaxLevel(@RequestBody SysApprove approveObj,
			HttpSession session) {
		boolean flag = true;
		try {
			approveService.sureSaveAppr(approveObj,session);
			// 调用消息提示的存储过程(审批结果提示给产品经理)
			flag = approveService.sureApproveShowMsg(approveObj.getDjId(), approveObj.getApproveLevel(),approveObj.getDsId(),session);
		} catch (Exception e) {
			e.printStackTrace();
			flag=false;
		}
		return flag;
	}

	/****
	 * 确定审批的保存
	 * @param apprObj
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("sureSaveApprove")
	@ResponseBody
	public ApproveReturnObj sureSaveAppr(
			@RequestBody ApproveReturnObj appReturnObj, HttpSession session)
	throws Exception {
		SysApprove approveObj = appReturnObj.getApproveObj();
		String dsId = appReturnObj.getDsId();
		String pkName = appReturnObj.getPkName(); // 主键名
		approveObj.setDsId(appReturnObj.getDsId());
		ApproveReturnObj reObj = new ApproveReturnObj();
		try {
			String verifyPass = "S001"; // 审批通过
			String verifyNoPass = "S002"; // 审批不通过
			String verifyRefuse = "S003"; // 驳回上一级(只有二审和三审有驳回上一级)
			String verifyReject = "S004"; // 审批被驳回(只有二审和三审有驳回上一级)
			String approveResutl = approveObj.getIsExamine(); // 审批的结果
			List<SysApprove> sysApproves = new ArrayList<SysApprove>();
			// 1.审批通过的时候
			if (approveResutl != null&& approveResutl.trim().equals(verifyPass)) { // 审批通过
				// 1.判断是不是最高的等级
				if (approveObj.getApproveLevel() == approveService.maxDjLevel(approveObj)) {// 如果当前等级等于最高等级，那么就把本单据的is_verify更新成1

					//一审被驳回或者一审不通过的时候也要验证再次提交的数据
					String isResult=approveService.checkApprovePass(approveObj.getApproveLevel(),appReturnObj.getDjId(),dsId,"");
					if(approveObj.getApproveLevel()==1&&isResult!=null&&(isResult.equals(verifyNoPass)||isResult.equals(verifyReject))){ 
						reObj.setMsg(approveService.checkSubmitData(appReturnObj.getDjId(),dsId, "", session));
					}
					else{
						reObj.setMsg("success");
						reObj.setCheckResult("success");
					}
					reObj.setDjIsVerify("1");
				}
				// 2.不是最高的等级,要把本单据的is_verify更新成下一等级的待审批
				else {
					Boolean flag=approveService.sureSaveAppr(approveObj,session);
					if (flag) { // 修改本级别的审批结果
						ReturnObject ro = approveService.updateIsVerify(approveObj.getApproveLevel(),approveObj.getDjId(),dsId,session);
						if(approveObj.getApproveLevel()==1){
							reObj.setCheckResult(ro.getMsg());
						}
						reObj.setDjIsVerify(ro.getIsVerify());
						reObj.setMsg("success");
					} else {
						reObj.setMsg("fail");
						throw new Exception("审批保存的时异常        #approveController 353");
					}
				}
			}
			// 审批不通过（如果当前级别是一审,那么就把一审的状态改成审批不通过,否则,把一审的审批结果改成审批被驳回,并且大于一审的级别到当前级别的所有的审批数据的标志位设置成空）
			else if (approveResutl != null&& approveResutl.trim().equals(verifyNoPass)) {
				if (approveService.sureSaveAppr(approveObj,session)) { // 修改本级别的审批结果
					reObj.setMsg("success");
				}
				ReturnObject ro  = approveService.updateIsVerify(approveObj.getApproveLevel(),approveObj.getDjId(), dsId,session);
				reObj.setDjIsVerify(ro.getIsVerify());
			}
			if(!"1".equals(reObj.getDjIsVerify())){
				//调用消息提示的存储过程
				boolean flag = approveService.sureApproveShowMsg(appReturnObj.getDjId(), appReturnObj.getApproveObj().getApproveLevel(),dsId, session);
				if (flag == false) {
					reObj.setMsg("fail");
					throw new Exception("该审批单据向消息,提示列表中插入信息失败");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			reObj.setMsg("fail");
		}
		return reObj;
	}


	/***
	 * 最高一级的领导审批通过之后确认驳回(驳回到保存的状态)
	 * @param session
	 * @return
	 * @author feifei
	 * @date: 2015-3-31 下午04:32:28 
	 */
	@RequestMapping("sureReject")
	@ResponseBody
	public ReturnObject sureReject(@RequestBody ApproveReturnObj aro, HttpSession session) throws Exception{
		ReturnObject reObject=new ReturnObject();
		SysApprove approveObj=aro.getApproveObj();
		try {
			reObject=approveService.sureRejectByLead(aro.getDjId(),aro.getDsId(),aro.getButnCode(),session);
			if (reObject==null||reObject.getIsResult().toString().toUpperCase().equals("SUCCESS")){
				//确认驳回成功，或者没有驳回的过程
				if (approveService.sureSaveAppr(approveObj,session)) { // 修改本级别的审批结果
					approveService.updateIsVerify(approveObj.getApproveLevel(),approveObj.getDjId(), aro.getDsId(),session);
				}else{
					throw new Exception("驳回失败");
				}
				//调用消息提示的存储过程
				boolean flag = approveService.sureApproveShowMsg(aro.getDjId(), aro.getApproveObj().getApproveLevel(),aro.getDsId(),session);
				if (flag == false) {
					throw new Exception("该审批单据向消息,提示列表中插入信息失败;");
				}
				reObject=new ReturnObject();
				reObject.setIsResult("success");
			}else{
				if(reObject.getMsg()==null||reObject.getMsg().trim().equals("")){
					reObject.setMsg("亲，改单据不能驳回");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			reObject.setIsResult("fail");
		}
		return reObject;
	}



	/***
	 * @return
	 * @throws Exception
	 * @author chenfeifei
	 * @version 创建时间：2014-10-18 下午07:47:47
	 */
	@RequestMapping("isApproveFlow")
	@ResponseBody
	public boolean isApproveFlow(String djId,String dsId, HttpServletRequest request,
			HttpSession session) throws Exception{
		boolean flag = false;
		// 得到该单据的最低等级的审批对象
		SysApprove sysApprove = approveService.getMinLevelAppObj(djId,dsId);
		if (sysApprove.getIsExamine() == null
				|| sysApprove.getIsExamine().trim() == "") {
			flag = true;
		}
		return flag;
	}


	/*****
	 * 删除流程环节
	 * @param regId
	 * @param curLevel
	 * @param flowId
	 * @param request
	 * @param session
	 * @throws Exception
	 * @author chenfeifei
	 * @version 创建时间：2014-12-3 下午03:29:52
	 */
	@RequestMapping("delApproveFlow")
	@ResponseBody
	public ReturnObject delApproveFlow(String regId, Integer curLevel,String flowId, HttpServletRequest request, HttpSession session)
	throws Exception {
		ReturnObject returnObject = new ReturnObject();
		try {
			returnObject.setMsg(approveService.delApproveFlow(regId, curLevel,flowId));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnObject;
	}




	/***
	 * 判断当前登录人是不是总裁
	 * @param djId
	 * @param dsId
	 * @param session
	 * @return
	 * @throws Exception
	 * @author feifei
	 * @date: 2015-4-13 下午06:10:33 
	 */
	@RequestMapping("getMaster")
	@ResponseBody
	public String getMaster(String djId,String dsId,HttpSession session) throws Exception{
		String isceo="";
		try {
			isceo=approveService.getMaster(djId, dsId, session);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return isceo;
	}

}
